//
//  AppDelegate.m
//  Visitor
//
//  Created by x on 2017/9/11.
//  Copyright © 2017年 HLB. All rights reserved.
//

#import "AppDelegate.h"
#import "GYLoginViewController.h"
#import "GYBaseNavigationController.h"
#import "GYMainTabBarController.h"
#import "GYNetWorkTools.h"

#import "UMessage.h"
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000
#import <UserNotifications/UserNotifications.h>
#endif

@interface AppDelegate ()<UNUserNotificationCenterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //#warning 程序未启动的时候  收到推送消息 点击  这样拿到推送消息的内容
    NSDictionary* userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (userInfo != nil) {
        //NSLog(@"设备ID:%@",[[[UIDevice currentDevice] identifierForVendor] UUIDString]);
        self.dic = userInfo;
    }
    
    //友盟
    //设置 AppKey 及 LaunchOptions
    [UMessage startWithAppkey:@"59cb4204c62dca582200015d" launchOptions:launchOptions httpsEnable:YES ];
    [UMessage openDebugMode:YES];
    //注册通知
    [UMessage registerForRemoteNotifications];
    //iOS10必须加下面这段代码。
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate=self;
    UNAuthorizationOptions types10=UNAuthorizationOptionBadge|UNAuthorizationOptionAlert|UNAuthorizationOptionSound;
    [center requestAuthorizationWithOptions:types10 completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            //点击允许
            NSLog(@"允许友盟推送...");
            
        } else {
            //点击不允许
            NSLog(@"不允许友盟推送...");
        }
    }];
    //开启日志打印
    [UMessage setLogEnabled:YES];
    
    
    //显示界面
    //1.监听更换跟控制器
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeRootController) name:@"changeRootController" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeRootController) name:@"loginOutSuccess" object:nil];
    
    //2.创建显示Window
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    //3.首先判断用户有没有登入过
    [self changeRootController];
    
    [self.window makeKeyAndVisible];
    
    return YES;
}

/**
 更换根控制器
 */
- (void)changeRootController {
    NSLog(@"changeRootController====");
    //3.首先判断用户有没有登入过
    if ([GYUserInfo loadUserInfo] == nil) {
        //没有登入
        GYBaseNavigationController *navi = [[GYBaseNavigationController alloc] initWithRootViewController:[[GYLoginViewController alloc] init]];
        
        self.window.rootViewController = navi;
    }else {
        //登入过
        GYMainTabBarController *mainTabBarController = [[GYMainTabBarController alloc] init];
        self.window.rootViewController = mainTabBarController;
    }
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    //1.首先判断key有没有失效
    [GYNetWorkTools loadUserInfo:^(NSDictionary *obj) {
        if ([[obj objectForKey:@"status"] intValue] == 200) {
            [[NSNotificationCenter defaultCenter]postNotificationName:@"updateVisitorInfo" object:nil];
        }else {
            //2.key失效,移除过期个人消息
            [GYUserInfo removeUserInfo];
            
            //3.更换控制器
            [self changeRootController];
        }
    } filed:^(NSError *error) {
        [SVProgressHUD showImage:nil status:@"网络可能不太通畅!"];
    }];
}

#pragma 推送事件

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    
//    NSLog(@"=====%@",[[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
//                  stringByReplacingOccurrencesOfString: @">" withString: @""]
//                 stringByReplacingOccurrencesOfString: @" " withString: @""]);
    
    NSString *device_token = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
                               stringByReplacingOccurrencesOfString: @">" withString: @""]
                              stringByReplacingOccurrencesOfString: @" " withString: @""];
    [[NSUserDefaults standardUserDefaults]setObject:device_token forKey:@"deviceToken"];
    //NSLog(@"pushToken======:%@", deviceToken);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    NSLog(@"1111111111111111");
    //关闭友盟自带的弹出框
    [UMessage setAutoAlert:NO];
    [UMessage didReceiveRemoteNotification:userInfo];
    //要通知界面加载最新数据
    [[NSNotificationCenter defaultCenter]postNotificationName:@"updateVisitorInfo" object:nil];
    NSLog(@"...............");
//    if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive) {
//        self.dic = userInfo;
//    }
}
//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        NSLog(@"iOS10新增：应用处于前台时的远程推送接受");
        [UMessage setAutoAlert:NO];
        //应用处于前台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        
        //要通知界面加载最新数据
        [[NSNotificationCenter defaultCenter]postNotificationName:@"updateVisitorInfo" object:nil];
    }else{
        //应用处于前台时的本地推送接受
    }
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}

//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        NSLog(@"iOS10新增：应用处于后台时的远程推送接受");
        //应用处于后台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        
        //要通知界面加载最新数据
        [[NSNotificationCenter defaultCenter]postNotificationName:@"updateVisitorInfo" object:nil];
        completionHandler();
    }else{
        //应用处于后台时的本地推送接受
    }
    
}




@end
